package acom.dhy.qigsaw2test.qigsaw

import android.app.Activity
import android.content.Context
import android.content.Intent
import androidx.activity.ComponentActivity
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContract
import com.dhy.xintent.XIntent
import com.dhy.xintent.putSerializableExtra
import com.dhy.xintent.readExtraList

class SplitResultContract : ActivityResultContract<DynamicFeature, List<String>?>() {
    override fun createIntent(context: Context, input: DynamicFeature): Intent {
        val intent = Intent(context, QigsawInstallerActivity::class.java)
        XIntent.with(intent).putSerializableExtra(input.moduleNames)
        return intent
    }

    override fun parseResult(resultCode: Int, intent: Intent?): List<String>? {
        if (resultCode != Activity.RESULT_OK) return null
        return XIntent.with(intent).readExtraList()
    }
}

fun ComponentActivity.registerForInstallSplitResult(): ActivityResultLauncher<DynamicFeature> {
    return registerForActivityResult(SplitResultContract()) { moduleNames ->
        if (moduleNames != null) {
            val feature = DynamicFeature.find(moduleNames)
            feature!!.onActivityResult(this)
        }
    }
}